<template>
  <t-card>
    <t-space direction="vertical" style="width: 100%">
      <t-form v-show="showSearch" ref="queryRef" :data="queryParams" layout="inline" reset-type="initial" label-width="calc(4em + 12px)" label-align="top">
        <t-form-item label="编号" name="participantsId">
          <t-input v-model="queryParams.participantsId" placeholder="请输入编号" clearable @enter="handleQuery" />
</t-form-item>
        <t-form-item label="参会人员名称" name="participantsName">
          <t-input v-model="queryParams.participantsName" placeholder="请输入参会人员名称" clearable @enter="handleQuery" />
</t-form-item>
        <t-form-item label="参会人员职务" name="participantsPosition">
          <t-input v-model="queryParams.participantsPosition" placeholder="请输入参会人员职务" clearable @enter="handleQuery" />
</t-form-item>
        <t-form-item label="参会人员性别" name="participantsSex">
          <t-select v-model="queryParams.participantsSex" placeholder="请选择参会人员性别" clearable>
            <t-option
              v-for="dict in participants_sex"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </t-select>
        </t-form-item>
        <t-form-item label="参会人员年龄" name="participantsAge">
          <t-input v-model="queryParams.participantsAge" placeholder="请输入参会人员年龄" clearable @enter="handleQuery" />
</t-form-item>
        <t-form-item label="参会人员电话" name="participantsPhone">
          <t-input v-model="queryParams.participantsPhone" placeholder="请输入参会人员电话" clearable @enter="handleQuery" />
</t-form-item>
        <t-form-item label="参会人员邮箱" name="participantsEmail">
          <t-input v-model="queryParams.participantsEmail" placeholder="请输入参会人员邮箱" clearable @enter="handleQuery" />
</t-form-item>
        <t-form-item label="参会人员描述" name="participantsContent">
          <t-input v-model="queryParams.participantsContent" placeholder="请输入参会人员描述" clearable @enter="handleQuery" />
</t-form-item>
        <t-form-item label="参会人员个人成就" name="participantsAchievement">
          <t-input v-model="queryParams.participantsAchievement" placeholder="请输入参会人员个人成就" clearable @enter="handleQuery" />
</t-form-item>
        <t-form-item label="参会人员类型" name="participantsType">
          <t-select v-model="queryParams.participantsType" placeholder="请选择参会人员类型" clearable>
            <t-option
              v-for="dict in participants_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </t-select>
        </t-form-item>
        <t-form-item label="创建时间">
          <t-date-range-picker
            v-model="dateRangeCreateTime"
            style="width: 240px"
            allow-input
            clearable
            separator="-"
            :placeholder="['开始日期', '结束日期']"
          />
        </t-form-item>
        <t-form-item label-width="0px">
            <t-space align="end" style="height: 64px">
                <t-button theme="primary" @click="handleQuery">
                    <template #icon> <search-icon /></template>
                    搜索
                </t-button>
                <t-button theme="default" @click="resetQuery">
                    <template #icon> <refresh-icon /></template>
                    重置
                </t-button>
            </t-space>
        </t-form-item>
      </t-form>

      <t-table
        v-model:column-controller-visible="columnControllerVisible"
        :loading="loading"
        hover
        row-key="participantsId"
        :data="participantsList"
        :columns="columns"
        :selected-row-keys="ids"
        select-on-row-click
        :pagination="pagination"
        :column-controller="{
          hideTriggerButton: true,
        }"
        :sort="sort"
        show-sort-column-bg-color
        @sort-change="handleSortChange"
        @select-change="handleSelectionChange"
      >
        <template #topContent>
          <t-row>
            <t-col flex="auto">
              <t-button v-hasPermi="['xhlj:participants:add']" theme="primary" @click="handleAdd">
                <template #icon> <add-icon /></template>
                新增
              </t-button>
              <t-button
                v-hasPermi="['xhlj:participants:edit']"
                theme="default"
                variant="outline"
                :disabled="single"
                @click="handleUpdate()"
              >
                <template #icon> <edit-icon /> </template>
                修改
              </t-button>
              <t-button
                v-hasPermi="['xhlj:participants:remove']"
                theme="danger"
                variant="outline"
                :disabled="multiple"
                @click="handleDelete()"
              >
                <template #icon> <delete-icon /> </template>
                删除
              </t-button>
              <t-button v-hasPermi="['xhlj:participants:export']" theme="default" variant="outline" @click="handleExport">
                <template #icon> <download-icon /> </template>
                导出
              </t-button>
              <span class="selected-count">已选 {{ ids.length }} 项</span>
            </t-col>
            <t-col flex="none">
              <t-button theme="default" shape="square" variant="outline" @click="showSearch = !showSearch">
                <template #icon> <search-icon /> </template>
              </t-button>
              <t-button theme="default" variant="outline" @click="columnControllerVisible = true">
                <template #icon> <setting-icon /> </template>
                列配置
              </t-button>
            </t-col>
          </t-row>
        </template>



        <template #conferenceInfo="{ row }">
            <span v-if="row.conferenceInfo && Object.keys(row.conferenceInfo).length > 1">
              {{ row.conferenceInfo[Object.keys(row.conferenceInfo)[1]] }}（编号为{{ row.conferenceInfo[Object.keys(row.conferenceInfo)[0]] }}）
            </span>
        </template>

        <template #sysUser="{ row }">
            <span v-if="row.sysUser && Object.keys(row.sysUser).length > 1">
              {{ row.sysUser[Object.keys(row.sysUser)[1]] }}（编号为{{ row.sysUser[Object.keys(row.sysUser)[0]] }}）
            </span>
        </template>


        <template #participantsAvatar="{ row }">
            <image-preview :src="row.participantsAvatar" :width="60" :height="60" />
        </template>

        <template #participantsSex="{ row }">
            <dict-tag :options="participants_sex" :value="row.participantsSex" />
        </template>






        <template #participantsType="{ row }">
            <dict-tag :options="participants_type" :value="row.participantsType" />
        </template>


        <template #operation="{ row }">
          <t-space :size="8" break-line>
            <t-link v-hasPermi="['xhlj:participants:query']" theme="primary" hover="color" @click.stop="handleDetail(row)">
              <browse-icon />详情
            </t-link>
            <t-link v-hasPermi="['xhlj:participants:edit']" theme="primary" hover="color" @click.stop="handleUpdate(row)">
              <edit-icon />修改
            </t-link>
            <t-link v-hasPermi="['xhlj:participants:remove']" theme="danger" hover="color" @click.stop="handleDelete(row)">
              <delete-icon />删除
            </t-link>
          </t-space>
        </template>
      </t-table>
    </t-space>
    <!-- 添加或修改参会人员对话框 -->
    <t-dialog
      v-model:visible="open"
      :header="title"
      destroy-on-close
      :close-on-overlay-click="false"
      width="1100px"
      attach="body"
      :confirm-btn="{
        loading: buttonLoading,
      }"
      @confirm="onConfirm"
    >
      <t-loading :loading="buttonLoading">
        <t-form
          ref="participantsRef"
          label-align="top"
          :data="form"
          :rules="rules"
          label-width="calc(5em + 41px)"
          scroll-to-first-error="smooth"
          @submit="submitForm"
        >

          <t-form-item label="参会人员名称" name="participantsName">
            <t-textarea v-model="form.participantsName" placeholder="请输入参会人员名称" />
          </t-form-item>

    <t-form-item label="大会" name="conferenceInfo">
        <t-select v-model="form.conferenceInfoId" :options="optionsXhljConferenceInfo" clearable placeholder="请选择大会">
            <template #panelTopContent>
                <div style="padding: 6px 6px 0 6px">
                    <t-textarea v-model="searchXhljConferenceInfo" placeholder="请输入关键词搜索" @change="onSearchXhljConferenceInfo" />
                </div>
            </template>
        </t-select>
    </t-form-item>

          <t-form-item label="参会人员职务" name="participantsPosition">
            <t-textarea v-model="form.participantsPosition" placeholder="请输入参会人员职务" />
          </t-form-item>

          <t-form-item label="参会人员头像" name="participantsAvatar">
            <image-upload v-model="form.participantsAvatar" :limit="0" />
          </t-form-item>

          <t-form-item label="参会人员性别" name="participantsSex">
            <t-radio-group v-model="form.participantsSex">
              <t-radio
                v-for="dict in participants_sex"
                :key="dict.value"
                :value="dict.value"
              >{{dict.label}}</t-radio>
            </t-radio-group>
          </t-form-item>

          <t-form-item label="参会人员年龄" name="participantsAge">
            <t-input-number v-model="form.participantsAge" placeholder="请输入" />
          </t-form-item>

          <t-form-item label="参会人员电话" name="participantsPhone">
            <t-textarea v-model="form.participantsPhone" placeholder="请输入参会人员电话" />
          </t-form-item>

          <t-form-item label="参会人员邮箱" name="participantsEmail">
            <t-textarea v-model="form.participantsEmail" placeholder="请输入参会人员邮箱" />
          </t-form-item>

          <t-form-item label="参会人员描述" name="participantsContent">
            <editor v-model="form.participantsContent" />
          </t-form-item>

          <t-form-item label="参会人员个人成就" name="participantsAchievement">
            <t-textarea v-model="form.participantsAchievement" placeholder="请输入参会人员个人成就" />
          </t-form-item>

          <t-form-item label="参会人员类型" name="participantsType">
            <t-select v-model="form.participantsType" placeholder="请选择参会人员类型" clearable>
              <t-option
                v-for="dict in participants_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </t-select>
          </t-form-item>
        </t-form>
      </t-loading>
    </t-dialog>

    <!-- 参会人员详情 -->
    <t-dialog
      v-model:visible="openView"
      header="参会人员详情"
      placement="center"
      width="800px"
      attach="body"
      :footer="false"
    >
      <my-descriptions :loading="openViewLoading">

        <t-descriptions-item label="编号">{{ form.participantsId }}</t-descriptions-item>

        <t-descriptions-item label="参会人员名称" :span="2">{{ form.participantsName }}</t-descriptions-item>

        <span v-if="form.conferenceInfo && Object.keys(form.conferenceInfo).length > 1">
              {{ form.conferenceInfo[Object.keys(form.conferenceInfo)[1]] }}（编号为{{ form.conferenceInfo[Object.keys(form.conferenceInfo)[0]] }}）
        </span>

        <span v-if="form.sysUser && Object.keys(form.sysUser).length > 1">
              {{ form.sysUser[Object.keys(form.sysUser)[1]] }}（编号为{{ form.sysUser[Object.keys(form.sysUser)[0]] }}）
        </span>

        <t-descriptions-item label="参会人员职务" :span="2">{{ form.participantsPosition }}</t-descriptions-item>

        <t-descriptions-item label="参会人员头像">
          <image-preview :src="form.participantsAvatar" :width="60" :height="60" />
        </t-descriptions-item>

        <t-descriptions-item label="参会人员性别">
          <dict-tag :options="participants_sex" :value="form.participantsSex" />
        </t-descriptions-item>

        <t-descriptions-item label="参会人员年龄">{{ form.participantsAge }}</t-descriptions-item>

        <t-descriptions-item label="参会人员电话" :span="2">{{ form.participantsPhone }}</t-descriptions-item>

        <t-descriptions-item label="参会人员邮箱" :span="2">{{ form.participantsEmail }}</t-descriptions-item>

        <t-descriptions-item label="参会人员描述" :span="2">
          <editor-preview :html-text="form.participantsContent" />
        </t-descriptions-item>

        <t-descriptions-item label="参会人员个人成就" :span="2">{{ form.participantsAchievement }}</t-descriptions-item>

        <t-descriptions-item label="参会人员类型">
          <dict-tag :options="participants_type" :value="form.participantsType" />
        </t-descriptions-item>

        <t-descriptions-item label="创建时间">{{ parseTime(form.createTime) }}</t-descriptions-item>

      </my-descriptions>
    </t-dialog>
  </t-card>
</template>
<script lang="ts" setup>
defineOptions({
  name: 'Participants',
});
import {
  AddIcon,
  BrowseIcon,
  DeleteIcon,
  DownloadIcon,
  EditIcon,
  RefreshIcon,
  SearchIcon,
  SettingIcon,
} from 'tdesign-icons-vue-next';
import type { SelectProps, TextareaProps, FormInstanceFunctions, FormRule, PageInfo, PrimaryTableCol, SubmitContext, TableSort } from 'tdesign-vue-next';
import { computed, getCurrentInstance, ref } from 'vue';
import { ArrayOps } from '@/utils/array';

import type { XhljParticipantsForm, XhljParticipantsQuery, XhljParticipantsVo } from '@/api/xhlj/model/participantsModel';
import { listParticipants, getParticipants, delParticipants, addParticipants, updateParticipants } from '@/api/xhlj/participants';
import type { XhljConferenceInfoQuery } from '@/api/xhlj/model/conferenceInfo';
import { listConferenceInfo } from '@/api/xhlj/conferenceInfo';
import Editor from '@/components/editor/index.vue';
import EditorPreview from '@/components/editor-preview/index.vue';


const { proxy } = getCurrentInstance();
const { participants_type, participants_sex } = proxy.useDict('participants_type', 'participants_sex');

const openView = ref(false);
const openViewLoading = ref(false);
const participantsRef = ref<FormInstanceFunctions>();
const open = ref(false);
const buttonLoading = ref(false);
const title = ref('');
const participantsList = ref<XhljParticipantsVo[]>([]);
const loading = ref(false);
const columnControllerVisible = ref(false);
const showSearch = ref(true);
const total = ref(0);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const sort = ref<TableSort>();


const queryParamsXhljConferenceInfo = ref<XhljConferenceInfoQuery>({
    pageNum: 1,
    pageSize: 10000,
});
const listXhljConferenceInfo = [];
const optionsXhljConferenceInfo = ref<SelectProps['options']>(listXhljConferenceInfo);
const searchXhljConferenceInfo = ref('');
const onSearchXhljConferenceInfo: TextareaProps['onChange'] = () => {
    optionsXhljConferenceInfo.value = listXhljConferenceInfo.filter((item) => item.label.indexOf(searchXhljConferenceInfo.value) !== -1);
};
/** 查询大会列表 */
function getConferenceInfoList() {
    listConferenceInfo(queryParamsXhljConferenceInfo.value)
        .then((response) => {
            response.rows.forEach((item) => {
                const option: SelectProps = {
                    label: item[Object.keys(item)[1]],
                    value: item[Object.keys(item)[0]],
                };
                listXhljConferenceInfo.push(option)
            });
            console.log("XhljConferenceInfo", response.rows)
            console.log("listXhljConferenceInfo", listXhljConferenceInfo)
        })
}











const dateRangeCreateTime = ref([]);


// 校验规则
const rules = ref<Record<string, Array<FormRule>>>({
});

// 列显隐信息
const columns = ref<Array<PrimaryTableCol>>([
  { title: `选择列`, colKey: 'row-select', type: 'multiple', width: 50, align: 'center' },
  { title: `编号`, colKey: 'participantsId', align: 'center', ellipsis: true },
  { title: `参会人员名称`, colKey: 'participantsName', align: 'center', ellipsis: true },
  { title: `大会`, colKey: 'conferenceInfo', align: 'center', minWidth: 100, ellipsis: true },
  { title: `系统用户`, colKey: 'sysUser', align: 'center', minWidth: 100, ellipsis: true },
  { title: `参会人员职务`, colKey: 'participantsPosition', align: 'center', ellipsis: true },
  { title: `参会人员头像`, colKey: 'participantsAvatar', align: 'center', width: 120 },
  { title: `参会人员性别`, colKey: 'participantsSex', align: 'center' },
  { title: `参会人员年龄`, colKey: 'participantsAge', align: 'center' },
  { title: `参会人员电话`, colKey: 'participantsPhone', align: 'center', ellipsis: true },
  { title: `参会人员邮箱`, colKey: 'participantsEmail', align: 'center', ellipsis: true },
  { title: `参会人员描述`, colKey: 'participantsContent', align: 'center', ellipsis: true },
  { title: `参会人员个人成就`, colKey: 'participantsAchievement', align: 'center', ellipsis: true },
  { title: `参会人员类型`, colKey: 'participantsType', align: 'center' },
  { title: `创建时间`, colKey: 'createTime', align: 'center', minWidth: 112, width: 120, sorter: true },
  { title: `操作`, colKey: 'operation', align: 'center', width: 120 },
]);
// 提交表单对象
const form = ref<XhljParticipantsVo & XhljParticipantsForm>({});
// 查询对象
const queryParams = ref<XhljParticipantsQuery>({
  pageNum: 1,
  pageSize: 10,
  participantsId: undefined,
  participantsName: undefined,
  participantsPosition: undefined,
  participantsAvatar: undefined,
  participantsSex: undefined,
  participantsAge: undefined,
  participantsPhone: undefined,
  participantsEmail: undefined,
  participantsContent: undefined,
  participantsAchievement: undefined,
  participantsType: undefined,
});
// 分页
const pagination = computed(() => {
  return {
    current: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    total: total.value,
    showJumper: true,
    onChange: (pageInfo: PageInfo) => {
      queryParams.value.pageNum = pageInfo.current;
      queryParams.value.pageSize = pageInfo.pageSize;
      getList();
    },
  };
});

/** 查询参会人员列表 */
function getList() {
  loading.value = true;
  proxy.addDateRange(queryParams.value, dateRangeCreateTime.value, 'CreateTime');
  listParticipants(queryParams.value)
    .then((response) => {
      participantsList.value = response.rows;
      total.value = response.total;
      console.log("Participants", response.rows)
    })
    .finally(() => (loading.value = false));
}

// 表单重置
function reset() {
  form.value = {};
  proxy.resetForm('participantsRef');
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRangeCreateTime.value = [];
  proxy.resetForm('queryRef');
  queryParams.value.pageNum = 1;
  handleSortChange(null);
}

/** 排序触发事件 */
function handleSortChange(value?: TableSort) {
  sort.value = value;
  if (Array.isArray(value)) {
    queryParams.value.orderByColumn = value.map((item) => item.sortBy).join(',');
    queryParams.value.isAsc = value.map((item) => (item.descending ? 'descending' : 'ascending')).join(',');
  } else {
    queryParams.value.orderByColumn = value?.sortBy;
    queryParams.value.isAsc = value?.descending ? 'descending' : 'ascending';
  }
  getList();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: Array<string | number>) {
  ids.value = selection;
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = '添加参会人员';
}

/** 详情按钮操作 */
function handleDetail(row: XhljParticipantsVo) {
  reset();
  openView.value = true;
  openViewLoading.value = true;
  const participantsId = row.participantsId;
  getParticipants(participantsId).then((response) => {
    form.value = response.data;
    openViewLoading.value = false;
  });
}

/** 修改按钮操作 */
function handleUpdate(row?: XhljParticipantsVo) {
  buttonLoading.value = true;
  reset();
  open.value = true;
  title.value = '修改参会人员';
  const participantsId = row?.participantsId || ids.value.at(0);
  getParticipants(participantsId).then((response) => {
    buttonLoading.value = false;
    form.value = response.data;
  });
}

/** 提交按钮 */
function onConfirm() {
  participantsRef.value.submit();
}

/** 提交表单 */
function submitForm({ validateResult, firstError }: SubmitContext) {
  if (validateResult === true) {
    buttonLoading.value = true;
    const msgLoading = proxy.$modal.msgLoading('提交中...');
    if (form.value.participantsId) {
      updateParticipants(form.value)
        .then(() => {
          proxy.$modal.msgSuccess('修改成功');
          open.value = false;
          getList();
        })
        .finally(() => {
          buttonLoading.value = false;
          proxy.$modal.msgClose(msgLoading);
        });
    } else {
      addParticipants(form.value)
        .then(() => {
          proxy.$modal.msgSuccess('新增成功');
          open.value = false;
          getList();
        })
        .finally(() => {
          buttonLoading.value = false;
          proxy.$modal.msgClose(msgLoading);
        });
    }
  } else {
    proxy.$modal.msgError(firstError);
  }
}

/** 删除按钮操作 */
function handleDelete(row?: XhljParticipantsVo) {
  const participantsIds = row?.participantsId || ids.value;
  proxy.$modal.confirm(`是否确认删除参会人员编号为${participantsIds}的数据项？`, () => {
    const msgLoading = proxy.$modal.msgLoading('正在删除中...');
    return delParticipants(participantsIds)
      .then(() => {
        ids.value = ArrayOps.fastDeleteElement(ids.value, participantsIds);
        getList();
        proxy.$modal.msgSuccess('删除成功');
      })
      .finally(() => {
        proxy.$modal.msgClose(msgLoading);
      });
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.addDateRange(queryParams.value, dateRangeCreateTime.value, 'CreateTime');
  proxy.download(
    'xhlj/participants/export',
    {
      ...queryParams.value,
    },
    `participants_${new Date().getTime()}.xlsx`,
  );
}

getList();
getConferenceInfoList();
</script>
